# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2025/6/7
desc: 
sample: 
"""
import json

from apitest.models import TestCase, EnvInfo, TestApiResult
from application.celery import app
from dvadmin.utils.RequestUtil import RequestUtil
from dvadmin.utils.string_util import load_json


@app.task
def task__api(**kargs):
    #场景 环境 {'case_id':1,'env_id':111}
    print(kargs)
    case_id = kargs.get('case_id')
    case = TestCase.objects.get(id=case_id)
    evn_id = kargs.get('env_id')
    apis = case.apis.all()
    api = RequestUtil()
    if evn_id is not None:
        env = EnvInfo.objects.get(id=evn_id)
        api.var_pool_data = json.loads(env.paramsbody)
    for request_data in apis:
        if request_data.get_method_display() == 'GET':
            api.send_request(request_data.get_method_display(), url=request_data.url,
                             headers=load_json(request_data.headers),
                             verification=request_data.verification, extract=request_data.extract)
        elif request_data.params is not None and request_data.params != "":
            params_dict = {}
            params = request_data.params.split("&")
            for p in params:
                ps = p.split("=")
                params_dict[ps[0]] = ps[1]
            api.send_request(request_data.get_method_display(), url=request_data.url,
                             headers=load_json(request_data.headers),
                             data=params_dict, verification=request_data.verification, extract=request_data.extract)
        else:
            api.send_request(request_data.get_method_display(), url=request_data.url,
                             headers=load_json(request_data.headers),
                             json=load_json(request_data.jsonbody), verification=request_data.verification,
                             extract=request_data.extract)
        print(api.get_result())
        result_data = api.get_result()
        testresult = TestApiResult()
        testresult.api_belong = request_data
        testresult.case_belong = case
        testresult.project_belong = request_data.project_belong
        testresult.module_belong = request_data.module_belong
        testresult.env_belong =evn_id
        testresult.took_time = result_data.get('took_time')
        testresult.verification = result_data.get('check_result')
        testresult.result = result_data.get('response')[:200]
        testresult.save()

